#!/bin/bash

#bash my.sh zhangsan Mainline 1.txt $token

gitee_id=$1
name=$2
add_rpmlist=$3
token=$4
old_dir=`pwd`

write_service()
{
cat > _service << EOF
<services>
    <service name="tar_scm_kernel_repo">
      <param name="scm">repo</param>
      <param name="url">next/openEuler/packagename</param>
    </service>
</services>
EOF
}


usage()
{
	if [ $# -ne 4 ];then
		echo 'Usage: bash my.sh gitee_id name add_rpmlist token'
		echo 'example: bash my.sh zhangsan Factory 1.txt 44ddcc33eewqdqw'
	        rm $old_dir/_service -rf
		exit 1
	fi
}

fork()
{
        curl -X POST --header 'Content-Type: application/json;charset=UTF-8' "https://gitee.com/api/v5/repos/src-openEuler/obs_meta/forks" -d "{\"access_token\":\"$token\"}" &>/dev/null && echo "fork yes"
	echo -n "ready to clone ? (y/n) "
        read to_clone
	if [ $to_clone == "y" ];then
		git clone https://gitee.com/${gitee_id}/obs_meta.git
	else
		echo 'The Program is exit...'
	        rm $old_dir/_service -rf
		exit 1
	fi
}

add_file()
{
	cd ./obs_meta/master/openEuler:${name} &> /dev/null
	for dir in $(cat ${old_dir}/${add_rpmlist});do
	       cd $dir &> /dev/null
	       if [ $? -eq 0 ]; then
		   cd - &> /dev/null
		   continue
	       else
		   mkdir $dir && cp $old_dir/_service $dir && cd $dir &> /dev/null
		   sed -i 's/packagename/'$dir'/g' _service 
	       fi
	       cd - &> /dev/null
	done

        git add -A
        git commit -m "add packages to openEuler:'${name}'"
	git status
	echo 'Are you ready to push ?(y/n)'
	read choose
	if [ $choose == 'y' ];then
		git push
	else
	        rm $old_dir/_service -rf
		exit 1
	fi
}

main()
{
        usage
	write_service
	if [ -d ./obs_meta ];then
		cd ./obs_meta && git pull && cd -
		add_file
	else
                fork
		add_file
	fi
	rm $old_dir/_service -rf
}

main
